# -*- coding: utf-8 -*-
'''考虑把term封装成类，用面向对象的方式实现以下函数
'''
from datetime import timedelta

from dateutil import parser

from common.utils import tz


def calc_term_by_ts(ts):
    '''通过绝对时间来计算期数，抓取時間後是下一期
    抓取時間是算下一期，有過天數的請注意
    '''
    prefix, start_ts = tz.get_day_and_start_ts(ts)
    sub = ts - start_ts

    if sub < 7380:
        term = (sub - 180) / 600 + 2
    elif sub < 36180:  # 2:03 ~ 10:02，第14期一直到10:03以後才会开奖
        term = 14
    else:
        '''
        if sub < 85380(23:43):
            term = 97
        if sub < 85980(23:53):
            term = 98 == 1
        '''
        term = (sub - 36180) / 600 + 15
    if term == 98 or term == 99:
        prefix = tz.get_next_day(ts)
        term = 1

    assert 1 <= term <= 97
    return '%s%s' % (prefix, str(term).zfill(3))


def _plus_term(day, real_term, offset):
    real_term += offset
    if real_term > 97:
        day += timedelta(real_term / 97)
        real_term %= 97
    elif real_term <= 0:
        day += timedelta(real_term / 97)
        real_term = (real_term - 1) % 97 + 1
    else:
        pass
    return day, real_term


def _format_term(day, real_term):
    return '%s%s' % (day.strftime('%Y%m%d'), str(real_term).zfill(3))


def plus_term(term, offset):
    '''计算期号，offset可以为负数
    '''
    if offset == 0:
        return term
    day, real_term = term[:8], int(term[8:])

    day, real_term = _plus_term(parser.parse(day), real_term, offset)
    return _format_term(day, real_term)


def xrange_term(term, count, step=1):
    '''生成器，根据plus term生成一个迭代器，类似xrange
    '''
    if step == 0:
        raise ValueError('step must be not 0')
    if count == 0:
        yield term
    cur_count = 0
    day, real_term = term[:8], int(term[8:])
    day = parser.parse(day)
    while abs(cur_count) < abs(count):
        cur_count += 1
        if cur_count == 1:
            yield term
        else:
            day, real_term = _plus_term(day, real_term, step)
            yield _format_term(day, real_term)


def calc_start_ts_by_term(term):
    '''通过期数计算开始时间，用来手动开启当前期数
    時間是當期
    '''
    prefix = term[:8]
    term = int(term[8:])
    start_ts = tz.to_ts(tz.local_to_utc(parser.parse(prefix)))
    if term == 1:
        term = 98
        # 第一期为明天日期，所以要扣掉一天时间戳
        start_ts -= 86400
        return start_ts + (term - 15) * 600 + 36180
    elif 1 < term < 15:
        return start_ts + (term - 2) * 600 + 180
    else:
        return start_ts + (term - 15) * 600 + 36180


def calc_stop_ts(start_ts):
    '''根据开始时间和当前的时间，来计算结束的时间，无偏移量
    '''
    term = calc_term_by_ts(start_ts)
    real_term = int(term[8:])
    # 因为02:03~10:03中间不开奖
    if real_term == 14:
        # 2:03~10:03 8 * 60 * 60
        return calc_start_ts_by_term(term) + 28800
    else:
        return calc_start_ts_by_term(term) + 600
